import axios, { AxiosResponse } from 'axios'
import Cookie from 'js-cookie'

const HEADER = 'Authorization'

const request = axios.create({
    baseURL: "/api",
    timeout: 10000,
})

request.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded'
request.defaults.headers.delete['Content-Type'] = 'application/x-www-form-urlencoded'
request.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'
request.defaults.headers.put['Content-Type'] = 'application/json;charset=utf-8'
request.defaults.headers.patch['Content-Type'] = 'application/json;charset=utf-8'

// request拦截器
request.interceptors.request.use(config => {
    // 是否设置token
    const unAuth = config.headers?.unAuth === 'true'
    let token = Cookie.get(HEADER)
    if (token && !unAuth && config.headers) {
        config.headers[HEADER] = `Bearer ${token}`
    }
    return config
})

request.interceptors.response.use((res: AxiosResponse<{ success: boolean, data: any, msg: string }, any>) => {
    let success = res.data.success === undefined ? true : res.data.success
    if (success) {
        return res.data
    }
    return Promise.reject(res)
}, error => {
    return Promise.reject(error.response)
})

export default request